package com.hc.wdj.spring;

import com.hc.wdj.core.error.CoreError;
import com.hc.wdj.core.exception.NotWebContextException;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author ryanwdj
 * @since 2024/11/14
 */
public class SpringMVCUtil {

    private SpringMVCUtil(){}

    public static HttpServletRequest getRequest(){
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if(servletRequestAttributes == null){
            throw new NotWebContextException(CoreError.CUSTOMER_ERROR, "非web上下文,无法获取HttpServletRequest");
        }
        return servletRequestAttributes.getRequest();
    }

    public static HttpServletResponse getResponse(){
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if(servletRequestAttributes == null){
            throw new NotWebContextException(CoreError.CUSTOMER_ERROR, "非web上下文,无法获取HttpServletResponse");
        }
        return servletRequestAttributes.getResponse();
    }

    /**
     * 判断当前是否处于Web上下文中
     * @return
     */
    public static boolean isWeb(){
        return RequestContextHolder.getRequestAttributes() != null;
    }
}
